package com.PictureSite.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.PictureSite.DatabaseAccess.PictureSiteCreatePostDAO;
import com.PictureSite.model.PictureSitePostModel;
import com.PictureSite.model.UserPost;


public class PictureSitePostController extends PictureSiteController {
	
	private PictureSiteCreatePostDAO dataStore;

	public PictureSitePostController(PictureSiteCreatePostDAO dataStore) {
		this.dataStore = dataStore;
	}

	public void loadSinglePost(PictureSitePostModel model, HttpServletRequest req, HttpServletResponse resp) throws Exception {
		//Need to remake and have servlet based parameter extraction.
		UserPost userPost = new UserPost();
		String id = req.getPathInfo().replace("/", "");
		userPost.setId(id);
		
		Map<String,Object> parameters = dataStore.getPostFromId(userPost);
		
		if (parameters == null) {
			throw new Exception("The id is invalid. Page not found.");
		}
		
		for (Map.Entry<String,Object> parameter : parameters.entrySet())
		{
		    if(parameter.getKey().toString().equals("date")) {
		    	userPost.setDatePosted(parameter.getValue().toString());
		    } else if(parameter.getKey().toString().equals("title")) {
		    	userPost.setTitle(parameter.getValue().toString());
		    } else if(parameter.getKey().toString().equals("userName")) {
		    	userPost.setUserName(parameter.getValue().toString());
		    } else if(parameter.getKey().toString().equals("blobId")) {
		    	userPost.setBlobId(parameter.getValue().toString());
		    } else if(parameter.getKey().toString().equals("likes")) {
		    	userPost.setVotes(Integer.parseInt(parameter.getValue().toString()));
		    }
		}
		userPost.setVoteType(dataStore.getVoteType(id));
		List<UserPost> userPosts = new ArrayList<UserPost>();
		userPosts.add(userPost);
		model.setUserPosts(userPosts);
		
		getTopPosts(model,dataStore);
		
	}
}
